package com.share.tool.generator.api.vm;

import com.share.common.constant.DirConstant;
import com.share.common.utils.JsonUtil;
import com.share.tool.generator.api.config.BaseInfo;
import com.share.tool.generator.api.model.CtrlInfo;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.List;
import java.util.Properties;

public class VelocityHtmlFormat {
    public static String convert(BaseInfo baseInfo, List<CtrlInfo> result) {

        final String template = "Api.vm";
        final String outFileName = DirConstant.TMP_DIR+File.separator + template + ".html";
        final String templateLoadingPath = new File(ClassLoader.class.getResource("/template/vm").getPath()).getPath();

        //输出文件定义
        File outFile = new File(outFileName);


        // 配置模版目录
        Properties prop = new Properties();
        prop.put(Velocity.FILE_RESOURCE_LOADER_PATH, templateLoadingPath);
        prop.put("input.encoding", "UTF-8");// 输入编码
        prop.put("output.encoding", "UTF-8");//输出编码

        prop.put(Velocity.RUNTIME_LOG,DirConstant.TMP_DIR+File.separator+Velocity.RUNTIME_LOG);/*设置日志文件*/

        Velocity.init(prop);

        VelocityContext context = new VelocityContext();
        /*传json不出问题,如果是java对象，可能会有问题*/
        context.put("baseInfo", JsonUtil.toJsonObj(baseInfo));
        context.put("result", JsonUtil.toJsonArr(result));

        Template temp = Velocity.getTemplate(template);

        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter(outFile));
            temp.merge(context, bw);
            bw.flush();
            bw.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        return outFile.getAbsolutePath();
    }
}
